<?php
/**
 * Dwz 表格助手
 *
 * @author xiemaomao@iwgame.com
 * @copyright Copyright (c) 2009 Green Shore (http://www.iwgame.com)
 * @version $Id: DwzTable.php 1082 2011-12-09 09:27:48Z mmxie $
 */
class IG_View_Helper_DwzTable extends Zend_View_Helper_HtmlElement
{

    protected $_checkBox = array('checked' => array());

    /**
     *
     * @param array $columns
     * @param array $rows
     * @param array $attrs
     * @param array $checkbox
     *  - name     string  键
     *  - key      string  value
     *  - checked  array   选中的
     *
     * @return string
     */
    public function dwzTable(array $columns, $rows = array(), array $attrs = array(),
        array $checkbox = null, $target = null)
    {
        if ($checkbox) {
            if (!isset($checkbox['name']) || !isset($checkbox['key'])) {
                throw new IG_Exception('未定义$checkbox 的属性(name|key)');
            }
            $this->_checkBox = $checkbox;
            $column = array(
                'title'    => '<input type="checkbox" class="checkboxCtrl"'
                            . 'group="' . $checkbox['name'] . '">',
                'function' => array($this, 'checkBox')
            );

            array_unshift($columns, $column);
        }
        $attrs += array('layoutH' => 48, 'class' => 'table', 'width' => '100%');
        $table = $this->view->table($columns, $rows, $attrs);

        if (!$target && isset($rows[0])) {
            $rowKeys = array_keys($rows[0]);
            $target = current($rowKeys);
        }
        foreach ($rows as $key => $row) {
            $table->setRowAttributes($key, array(
                'target' => $target,
                'rel'    => $row[$target]
            ));
        }

        return $table;
    }

    public function checkBox($row, $table)
    {
        $checked = in_array($row[$this->_checkBox['key']], $this->_checkBox['checked'])
                 ? 'checked="checked"' : '';
        return '<input type="checkbox" '
             . 'name="' . $this->_checkBox['name'] . '" '
             . 'value="' . $row[$this->_checkBox['key']] . '" '
             . $checked
             . '/>';
    }
}